import MySQLdb
import logging
import os

class MySQLWrapper():
  def __init__(self):
    self.db = None
    self.host = None
    self.user = None
    self.password = None
    self.conn = None
    self.cursor = None

  def _execute(self, cmd):
    try:
      self.cursor.execute(cmd)
    except Exception, e:
      logging.info('Error execute database command %s' % (str(e)))
 
  def setParam(self, host, user, password, db):
    self.db = db
    self.host = host
    self.user = user
    self.password = password

  def connect(self):
    if self.db is not None:
      try:
        self.conn = MySQLdb.connect(host, user, password, db)
      except MySQLdb.Error, e:
        print "Error %d: %s" % (e.args[0], e.args[1])
        sys.exit(1)
      self.cursor = self.conn.cursor()

  def disconnect(self):
    if self.conn is not None:
       self.cursor.close()
       self.conn.close()

  def create(self, tableName, schema)
    cmd = "CREATE TABLE %s (%s)" % (tableName, schema)
    self._execute(cmd)

  def insert(self, tableName, names, vals):
    cmd = "INSERT INTO %s (%s) VALUES %s" % (tableName, names, vals)
    self._execute(cmd)

  def insertOne(self, tableName, name1, val1):
    cmd = "INSERT INTO %s (%s) VALUES %s" % (tableName, name1, val1)
    self._execute(cmd)

  def insertPair(self, tableName, name1, name2, val1, val2):
    cmd = "INSERT INTO %s (%s, %s) VALUES (%s, %s)"
        % (tableName, name1, name2, val1, val2)
    self._execute(cmd)

  def insertTriple(self, tableName,
                   name1, name2, name3,
                   val1, val2, val3):
    cmd = "INSERT INTO %s (%s, %s, %s) VALUES (%s, %s, %s)"
        % (tableName,
           name1, name2, name3,
           val1, val2, val3)
    self._execute(cmd)

  def existItem(self, tableName, name, vals):
    cmd = "SELECT 1 FROM %s WHERE %s=%s" % (tableName, name, vals)
    try:
      self.cursor.execute(cmd)
      res = self.cursor.fetchall()
      if len(res) > 0:
        return True
      else:
        return False
    except Exception, e:
      return False

  def existItemPred(self, tableName, predicate):
    cmd = "SELECT 1 FROM %s WHERE %s" % (tableName, predicate)
    try:
      self.cursor.execute(cmd)
      res = self.cursor.fetchall()
      if len(res) > 0:
        return True
      else:
        return False
    except Exception, e:
      return False 
